package club.fuwenhao.handler;

import club.fuwenhao.bean.BaseMsg;
import club.fuwenhao.netty.BaseNettyClientHandler;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * @program: fwh-netty
 * @description: 专属处理类---可以考虑扩展接口形式
 * @author: fwh
 * @date: 2021-10-28 10:35
 **/
@Slf4j
@ChannelHandler.Sharable
public class FwhNettyClientHandler extends BaseNettyClientHandler {
    /**
     * 空闲次数
     */
    private int idle_count = 1;

    /**
     * 循环次数
     */
    private int fcount = 1;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("本地地址为:{},远程地址为:{},上线成功", ctx.channel().localAddress(), ctx.channel().remoteAddress());
    }

    /**
     * 关闭连接触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("关闭连接时间:{},本地地址:{},远程地址:{}", new Date(), ctx.channel().localAddress(), ctx.channel().remoteAddress());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseMsg msg) throws Exception {
        log.info("服务端地址为:{}", ctx.channel().remoteAddress());
        log.info("接收服务端消息为:{}", msg.toString());
    }

    /**
     * 客户端心跳检测
     *
     * @param ctx
     * @param evt
     * @return void
     * @author fuwenhao
     * @date 2021/10/29 12:17 下午
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        log.info("客户端循环请求的时间:{}, 次数:{}", new Date(), fcount);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            //如果写通道处于空闲状态,就发送心跳命令
            if (IdleState.WRITER_IDLE.equals(event.state())) {
                //设置发送次数
                if (idle_count <= 3) {
                    idle_count++;
                    ctx.channel().writeAndFlush("hb_request");
                } else {
                    log.info("不再发送心跳请求了！");
                }
                fcount++;
            }
        }
    }
}
